package com.hoow.shakoow.launch

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.hoow.shakoow.ProjectConfig
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityAppUpdateBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.utils.update.ZHIVersionClient
import com.hoow.shakoow.utils.update.ZHIVersionIMPL


/** 启动页 */
@SuppressLint("CustomSplashScreen")
class AppUpdateActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityAppUpdateBinding

    //请求安装未知源权限code
    private val RC_INSTALL_PCK = 10086

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.app_update.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding =
            ActivityAppUpdateBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onContentViewBinded() {
        try {
            //如果已打开，就退出
            if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
                finish()
                return
            }

            //点击安装
            mActivityBinding.btnInstall.setOnClickListener {
                //安装文件
                ZHIVersionIMPL.startInstallApk(ZHIVersionIMPL.getApkSavePath())
            }

            //点击取消
            mActivityBinding.btnCancel.setOnClickListener {
                finish()
            }

            //检查权限
            startCheckPermissions()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RC_INSTALL_PCK) {
            //开始下载
            startCheckPermissions()
        }
    }

    /**
     * 1.先检查权限
     */
    fun startCheckPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (packageManager.canRequestPackageInstalls()) {
                //开始下载
                startFileDownLoad()
            } else {
                getUnknowAppInstallPage()
            }
        } else {
            //开始下载
            startFileDownLoad()
        }
    }

    /**
     * 2.先检查权限-安装未知源
     */
    fun getUnknowAppInstallPage() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                intent.data = Uri.parse("package:" + ProjectConfig.Pck)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityForResult(intent, RC_INSTALL_PCK)
            } else {
                //开始下载
                startFileDownLoad()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 3.开始下载
     */
    @SuppressLint("SetTextI18n")
    fun startFileDownLoad() {
        ZHIVersionClient.startDownload(ZHIVersionIMPL.productLink) { currentBytes, contentLength, done ->
            val progress = (currentBytes * 100 / contentLength).toInt()
            mActivityBinding.pbProgress.progress = progress
            mActivityBinding.tvProgress.text = "$progress%"
            mActivityBinding.tvProgress.visibility = View.VISIBLE

            mActivityBinding.btnInstall.visibility =
                if (done) View.VISIBLE else View.GONE
            mActivityBinding.btnCancel.visibility =
                if (done) View.VISIBLE else View.GONE

            if (done) {
                //安装文件
                ZHIVersionIMPL.startInstallApk(ZHIVersionIMPL.getApkSavePath())
            }
        }
    }
}